package com.wsh.sys.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wsh.dto.sys.DictDto;
import com.wsh.entity.sys.DictEntity;
import com.wsh.mapper.sys.DictDao;
import com.wsh.sys.DictTypeService;
import com.wsh.utils.PageUtils;
import com.wsh.sys.DictService;
import com.wsh.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Author 王思涵
 * @Date 2019/8/10
 * @Version 1.0
 * @Desciption
 **/
@Service
public class DictServiceImpl extends ServiceImpl<DictDao, DictEntity> implements DictService {

    @Autowired
    private DictTypeService dictTypeService;

    @Override
    public IPage<DictEntity> getList(DictDto dictDto) {
        // 分页数据处理
        IPage<DictEntity> pages = PageUtils.getPage(dictDto);

        String dictType = dictDto.getDictType();
        String code = dictDto.getCode();
        String dictValue = dictDto.getDictValue();

        // 分页查询处理
        IPage<DictEntity> page =  baseMapper.selectPage(pages, new QueryWrapper<DictEntity>()
                .like(StringUtils.isNotBlank(dictValue), "dict_value", dictValue)
                .eq(StringUtils.isNotBlank(code), "code", code)
                            .eq("book_type", dictType)
                            .orderByAsc("dict_order"));

        return page;
    }

    @Override
    public List<DictEntity> getDictByType(String type) {
        return baseMapper.getDictByType(type);
    }

    @Override
    public Map<String, List<DictEntity>> getDIctByTypes(String[] types) {
        Map<String, List<DictEntity>> dictMaps = new HashMap<>();
        List<DictEntity> dictEntities = baseMapper.getDIctByTypes(types);

        // 字典分组
        dictEntities.stream().forEach((e) -> {
            String bookType = e.getBookType();
            List<DictEntity> bookTypeList = dictMaps.get(bookType);
            if (!(bookTypeList != null && bookTypeList.size() > 0)) {
                bookTypeList = new ArrayList<>();
            }
            bookTypeList.add(e);
            dictMaps.put(bookType, bookTypeList);
        });
        return dictMaps;
    }

    @Override
    public Boolean checkChildren(String formId) {
        int book_type = this.count(new QueryWrapper<DictEntity>().eq("book_type", formId));
        return book_type > 0;
    }
}
